<template>
  <MyDrawer ref="myRef" title="分类" :disabled="false" @submit="submit">
    <el-form :model="drawerProps.row" label-width="120" :rules="rules" ref="formRef">
      <el-form-item label="分类名称">
        <el-input v-model="drawerProps.row.name"></el-input>
      </el-form-item>
      <el-form-item label="介绍" v-if="drawerProps.isNeedIntroduce">
        <el-input
          type="textarea"
          placeholder="请输入分类介绍"
          maxlength="200"
          :show-word-limit="true"
          v-model="drawerProps.row.introduce"
        ></el-input>
      </el-form-item>
      <el-form-item label="排序值">
        <el-input-number v-model="drawerProps.row.sort" :min="1" :max="1000"></el-input-number>
      </el-form-item>
    </el-form>
  </MyDrawer>
</template>

<script setup lang="ts">
import MyDrawer from "@/components/MyDrawer/index.vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { ref } from "vue";

const myRef = ref<InstanceType<typeof MyDrawer> | null>();

interface DrawerProps {
  row: any;
  api?: (params: any) => Promise<any>;
  getTable?: () => Promise<any>;
  isNeedIntroduce: boolean;
}

const rules: FormRules = {
  name: [
    { required: true, message: "分类名称是必须的", trigger: "blur" },
    { max: 20, min: 1, message: "字数在1-20之间", trigger: "blur" }
  ]
};

const initData: any = {
  name: "",
  sort: 1
};

const drawerProps = ref<DrawerProps>({ row: JSON.parse(JSON.stringify(initData)), isNeedIntroduce: false });

const acceptParams = (params: any) => {
  drawerProps.value = params;
  myRef.value?.acceptParams();
};

const formRef = ref<FormInstance>();

const submit = () => {
  if (!formRef.value) return;
  formRef.value.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success("成功");
      await drawerProps.value.getTable!();
      myRef.value?.close();
    } catch (error) {}
  });
};

defineExpose({ acceptParams });
</script>

<style></style>
